let app = getApp();
var base64 = require('../../utils/base64.js');
Page({
  /**  
   * 页面的初始数据 
   */
  data: {
    goods_base: '',//所购商品信息
    address_id: '',//地址id
    k: '',
    u: '',
    user_address_contact: '',//收货人姓名
    user_address_phone: '',//收货人电话
    shop_id:'',
    remark: "",
    is_show_time: 1,
    hd: 'pay_add',
    count_price: '',//合计金额
    is_add: false,
    switch1Checked: false,
    pay_way:1,//支付方式默认在线支付
    order: '',//所有信息
    orderAmount: 0,//订单金额
    memberDiscount: 0,//会员折扣额
    minPurchaseQuantity: 0,//最小购买数
    voucherDiscountMsg: '',//店铺代金券信息
    isUseMemberDiscount: 0,//是否使用会员折扣
    isUserOptOutVoucher: 0,//用户选择不使用店铺代金券
    voucherId: 0,//店铺代金券
    paymentMethod: 1,//支付方式
    voucherDiscount: 0, //店铺代金券折扣额
    numbers: 1,//购买数量
    chain_id: '',
    cart_id: '',
    discountedOrderAmount:0,//参与优惠后的金额
    ziti:true,
    redPacketDiscountMsg: '',//平台红包信息
    isUserOptOutRedPacket:0, //用户选择不使用平台红包
    redPacketDiscount:0, //平台红包折扣额
    redPacketId:0, //平台红包
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    new app.ToastPannel();
    that.getUserDefaultAddress();
    var goods_id = options.goods_id
    var chain_id = options.chain_id
    
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');

    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=confirmChain&typ=json',
      method: 'GET',
      data: { k: k, u: u, goods_id: goods_id, chain_id: chain_id, voucherId: that.data.voucherId, isGetBestOffer: 1 },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        var order = res.data.data;
        var goods_base = res.data.data.goods_base;
        var voucherId = order.bestOffer.voucherId;//店铺代金券
        var voucherDiscount = order.bestOffer.voucherPrice; //店铺代金券折扣额
        var voucherDiscountMsg = '';
        var minPurchaseQuantity = that.data.minPurchaseQuantity;
        var redPacketId = order.bestOffer.redPackId;//店铺红包id
        var redPacketDiscount = order.bestOffer.redPackPrice;//店铺红包金额
        var redPacketDiscountMsg = ''
        if (that.data.isUseMemberDiscount == 0) {
          if (order.enabledVoucher == 0) {
            voucherDiscountMsg = '暂无可使用的代金券';
          }
          if (order.enabledRedPacket == 0){
            redPacketDiscountMsg = '暂无可使用的平台红包';
          }
        }
        if (voucherId) {
          for (var i in order.voucherList) {
            if (order.voucherList[i].id == voucherId) {
              voucherDiscountMsg = "满" + order.voucherList[i].voucher_limit + "减" + order.voucherList[i].voucher_price;
              voucherDiscount = order.voucherList[i].voucher_price;
            }
          }
        }
        if (redPacketId){
          for (var i in order.redPacketList) {
            if (order.redPacketList[i].id == redPacketId) {
              redPacketDiscountMsg = "满" + order.redPacketList[i].redpacket_t_orderlimit + "减" + order.redPacketList[i].redpacket_price;
              redPacketDiscount = order.redPacketList[i].redpacket_price;
            }
          }
        }
        if (voucherDiscount && order.goodsPromotionStatus == 0){
          if (redPacketDiscount){
            var discountedOrderAmount = Number(order.orderAmount) - Number(voucherDiscount) - Number(redPacketDiscount);
          }else{
            var discountedOrderAmount = Number(order.orderAmount) - Number(voucherDiscount);
          }
        }else{
          if (redPacketDiscount && order.goodsPromotionStatus == 0){
            var discountedOrderAmount = Number(order.orderAmount) - Number(redPacketDiscount);
          }else{
            var discountedOrderAmount = order.orderAmount;
          }
        }
        
        if (order.goods_base.lower_limit == undefined) {
          minPurchaseQuantity = 0
        } else {
          minPurchaseQuantity = order.goods_base.lower_limit
        }
        if (order.goodsPromotionStatus > 0){
          voucherId = 0
          redPacketId = 0
          voucherDiscount = 0
          redPacketDiscount = 0
        }
        // 更新数据  
        that.setData({
          order: order,
          goods_base: goods_base,
          k: k,
          u: u,
          is_show_time: 0,
          voucherId: voucherId,
          discountedOrderAmount: discountedOrderAmount,
          chain_id: chain_id,
          cart_id: order.cart.cart_id,
          minPurchaseQuantity: minPurchaseQuantity,
          voucherDiscountMsg: voucherDiscountMsg,
          memberDiscount: order.memberDiscount,
          voucherDiscount: voucherDiscount,
          orderAmount: order.orderAmount,
          shop_id:order.shop_base.id,
          redPacketId: redPacketId,
          redPacketDiscount: redPacketDiscount,
          redPacketDiscountMsg: redPacketDiscountMsg
        });
      }
    })

  },
  //减数量
  reduce: function () {
    var that = this
    var num = Number(that.data.numbers) - 1
    var memberDiscount = that.data.memberDiscount
    var voucherDiscount = that.data.voucherDiscount
    var redPacketDiscount = that.data.redPacketDiscount
    if (that.data.numbers <= 1) {
      that.show('该商品最少需要购买1件')
      return false
    } else if (that.data.minPurchaseQuantity > 0 && num < that.data.minPurchaseQuantity) {
      that.show("该商品最少需要购买" + that.data.minPurchaseQuantity + '件')
      return false
    } else {
      
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
        method: 'GET',
        data: { k: that.data.k, u: that.data.u, cart_id: that.data.cart_id, chainId: that.data.chain_id, num: num },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          if (res.data.status == 200) {
            var orderAmount = res.data.data.price
            var discountedOrderAmount = orderAmount
            if (that.data.order.user_rate < 1) {
              memberDiscount = Number(orderAmount) - orderAmount * that.data.order.user_rate;
              if (memberDiscount > 0.01) {
                memberDiscount = memberDiscount
              } else {
                memberDiscount = 0
              }
              if (that.data.isUseMemberDiscount == 1) {
                 discountedOrderAmount = orderAmount - memberDiscount
              }
            } 
            if (that.data.isUseMemberDiscount == 0 && that.data.voucherId > 0 && that.data.isUserOptOutVoucher == 0){
              if (that.data.redPacketId > 0 && that.data.isUserOptOutRedPacket == 0){
                 discountedOrderAmount = Number(orderAmount) - Number(voucherDiscount) - Number(redPacketDiscount);
              }else{
                 discountedOrderAmount = Number(orderAmount) - Number(voucherDiscount);
              }
            }else{
              if (that.data.isUseMemberDiscount == 0 && that.data.redPacketId > 0 && that.data.isUserOptOutRedPacket == 0){
                 discountedOrderAmount = Number(orderAmount) - Number(redPacketDiscount);
              }
            }
            that.setData({
              orderAmount: orderAmount.toFixed(2),
              memberDiscount: memberDiscount,
              numbers: num,
              discountedOrderAmount: discountedOrderAmount
            });

          }
        }
      });
    }
  },
  //加数量
  add: function () {
    var that = this
    var memberDiscount = that.data.memberDiscount
    var num = Number(that.data.numbers) + 1
    var voucherDiscount = that.data.voucherDiscount
    var redPacketDiscount = that.data.redPacketDiscount
    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Cart&met=editCartNum&typ=json',
      method: 'GET',
      data: { k: that.data.k, u: that.data.u, cart_id: that.data.cart_id, chainId: that.data.chain_id, num: num },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.status == 200) {
          var orderAmount = res.data.data.price
          var discountedOrderAmount = orderAmount
          if (that.data.order.user_rate < 1) {
            memberDiscount = Number(orderAmount) - orderAmount * that.data.order.user_rate;
            if (memberDiscount > 0.01) {
              memberDiscount = memberDiscount
            } else {
              memberDiscount = 0
            }
            if (that.data.isUseMemberDiscount == 1) {
              var discountedOrderAmount = orderAmount - memberDiscount
            }
          }
          if (that.data.isUseMemberDiscount == 0 && that.data.voucherId > 0 && that.data.isUserOptOutVoucher == 0) {
            if (that.data.redPacketId > 0 && that.data.isUserOptOutRedPacket == 0) {
              discountedOrderAmount = Number(orderAmount) - Number(voucherDiscount) - Number(redPacketDiscount);
            } else {
              discountedOrderAmount = Number(orderAmount) - Number(voucherDiscount);
            }
          } else {
            if (that.data.isUseMemberDiscount == 0 && that.data.redPacketId > 0 && that.data.isUserOptOutRedPacket == 0) {
              discountedOrderAmount = Number(orderAmount) - Number(redPacketDiscount);
            }
          }

          that.setData({
            orderAmount: orderAmount.toFixed(2),
            memberDiscount: memberDiscount,
            numbers: num,
            discountedOrderAmount: discountedOrderAmount
          });
        }
      }
    });
  },
  //地址请求操作
  getUserDefaultAddress: function () {
    var that = this
    var k = wx.getStorageSync('key');
    var u = wx.getStorageSync('u');
    wx.request({
      url: app.configData.shop.api_url + '/index.php?ctl=Buyer_User&met=getUserConfigAddress&typ=json',
      method: 'GET',
      data: { k: k, u: u },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
       
        if (res.data.status == 200) {
          that.setData({
            address_id: res.data.data.user_address_id,
            user_address_contact: res.data.data.user_address_contact,
            user_address_phone: res.data.data.user_address_phone,
          });
        }
      }
    });
  },
  //留言
  liuyan: function (e) {
    var that = this
    var remark = e.detail.value
    this.setData({
      remark: remark
    })
  },
  // 清空买家留言内容
  clear: function () {
    var that = this
    that.setData({
      remark: ''
    })
  },
  //  添加新地址
  add_address: function () {
    wx.navigateTo({
      url: '../address_select/address_select?typ=ziti'
    })
  },
  //选择新地址
  address_select: function () {
    wx.navigateTo({
      url: '../address_select/address_select?typ=ziti'
    })
  },

 
  //支付
  formSubmit: function (e) {
    var that = this
    var arr = that.data.glistAll
    var pay_way = e.detail.target.dataset.pay_way
    that.setData({
      pay_way: pay_way,
      ziti: false
    })
    if (that.data.address_id == '') {
      that.show("请选择收货地址")

    } else {
      // 获取收货地址数据
      wx.request({
        url: app.configData.shop.api_url + '/index.php?ctl=Buyer_Order&met=addOrder&typ=json',
        method: 'GET',
        data: {
          k: that.data.k,
          u: that.data.u,
          receiver_name: that.data.user_address_contact,
          receiver_phone: that.data.user_address_phone,
          cart_id: that.data.cart_id,
          shop_id: that.data.shop_id,
          pay_way_id: that.data.pay_way,
          remark: that.data.remark,
          wxapp: 'wxapp',
          is_discount: that.data.isUseMemberDiscount,
          voucher_id: that.data.voucherId,
          chain_id:that.data.chain_id,
          redpacket_id: that.data.redPacketId
        },
        header: {
          'content-type': 'application/json'
        },
        success: function (res) {
          
          if (res.data.status == 200) {
            if (that.data.pay_way == 3) {
              wx.redirectTo({
                url: '../chain_order_list/chain_order_list'
              })
            } else {
              that.pay(res.data.data.uorder)
            }
          } else {
            that.show("支付失败,请重新支付")
          }
        }
      })
    }
  },
  //微信支付接口
  pay: function (uorder_id) {
    var that = this
    var openid = wx.getStorageSync('openid');
    wx.request({
      url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=createWXOrder&typ=json',
      method: 'GET',
      data: {
        k: that.data.k,
        u: that.data.u,
        uorder_id: uorder_id,
        openid: openid,
        trade_type: 'WXAPP'
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        wx.requestPayment({
          'timeStamp': res.data.timeStamp,
          'nonceStr': res.data.nonceStr,
          'package': res.data.package,
          'signType': 'MD5',
          'paySign': res.data.paySign,
          'success': function (res) {
            that.show('支付成功');
            wx.request({
              url: app.configData.paycenter.api_url + '/index.php?ctl=Pay&met=order_status&typ=json',
              method: 'GET',
              data: {
                k: that.data.k,
                u: that.data.u,
                order_id: uorder_id,
                buyer_id: that.data.u,
              },
              header: {
                'content-type': 'application/json'
              },
              success: function (res) {
                wx.redirectTo({
                  url: '../chain_order_list/chain_order_list'
                })
              }
            })
          },
          'fail': function (res) {
            wx.redirectTo({
              url: '../chain_order_list/chain_order_list'
            })
          },
          'complete': function (res) {
            wx.redirectTo({
              url: '../chain_order_list/chain_order_list'
            })
          }
        });
      }

    })

  },

  off: function () {
    this.setData({
      is_add: false
    })
  },

  //跳转到代金券页面
  store_voucher_get: function () {
    wx.navigateTo({
      url: '../store_voucher_get/store_voucher_get?typ=ziti',
    })
  },
  //会员折扣切换
  switch1Change: function () {
    var that = this
    var discountedOrderAmount = that.data.discountedOrderAmount
    var memberDiscount = that.data.memberDiscount
    var voucherDiscount = that.data.voucherDiscount
    var redPacketDiscount = that.data.redPacketDiscount
    if (that.data.isUseMemberDiscount == 0) {
      discountedOrderAmount = Number(discountedOrderAmount) + Number(voucherDiscount) + Number(redPacketDiscount) - Number(memberDiscount);
      // 更新数据  
      
      that.setData({
        discountedOrderAmount: discountedOrderAmount,
        isUseMemberDiscount: 1,
        switch1Checked: true,
      });

    } else {
      discountedOrderAmount = Number(discountedOrderAmount) + Number(memberDiscount) - Number(voucherDiscount) - Number(redPacketDiscount);
      // 更新数据  
      that.setData({
        discountedOrderAmount: discountedOrderAmount,
        isUseMemberDiscount: 0,
        switch1Checked: false,
      });
    }
  },
  //跳转到平台红包页面
  red_packet: function (e) {
    wx.navigateTo({
      url: '../red_packet_get/red_packet_get?typ=ziti',
    })
  }

})